package app.netant.finishbook.ymwen;

import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import app.netant.NetAntBase;

public class YmwenNetDetail extends NetAntBase {

	private YmwenNetEntity entity;
	private boolean isCharset = true;
	
	public YmwenNetDetail(String netSite) {
		super(netSite);
	}
	
	public void setEntity(YmwenNetEntity entity){
		this.entity = entity;
	}
	
	public void analyseTitle(){
		
		Elements activePart = document.select("#content #detail-box .detail-cols.fn-clear .ui_bg6 .box_intro table.ui_tb1 h1.f20h");
		String title = "";
		if(activePart.size()>0){
			
			String str = activePart.get(0).text();
			
			int point = str.indexOf("作者");
			if(point > -1){
				title = str.substring(0,point);
			}
			
			this.entity.setNovelName(title);
		}
		
	}
	
	public void analyseMemo(){
		
		Elements activePart = document.select("#content #detail-box .detail-cols.fn-clear .ui_bg6 .box_intro table.ui_tb1 tr td .intro");
		
		String memo = "";
		if(activePart.size()>0){
			
			memo = this.getString(activePart.get(0).text());

			this.entity.setNovelMemo(memo);
			
		}
		
	}
	
	protected String getString(String src){
		
		if(src == null || "".equals(src)){
			return src;
		}
		
		src = src.trim();
		
		return src.replaceAll("'", "’")
				  .replaceAll("\"", "”")
				  .replaceAll("&nbsp;", "")
				  .replaceAll("<br>", "")
				  .replaceAll("<br/>", "")
				  .replaceAll("<p>", "")
				  .replaceAll("</p>", "");
	}
	
	
	public void analyseTags(){
		
		Elements activePart = document.select("#content #detail-box .detail-cols.fn-clear .ui_bg6 .box_intro table.ui_tb1 tr");
		if(activePart.size()>0){
			int num = activePart.size();
			for(int i=num-2;i<num;i++){
				Element activeTR = activePart.get(i);
				Elements activeTDs = activeTR.select("td");
				if(activeTDs.size()>0){
					for(int j=0;j<activeTDs.size();j++){
						
						String tags = activeTDs.get(j).text();					
						
						String tagName = "";
						String tagValue = "";
						
						int index = tags.indexOf("：");
						
						if(index > -1){
							tagName = tags.substring(0,index).trim();
							tagValue = tags.substring(index+1).trim();						
							this.entity.setTag(tagName, tagValue);
						}
				
					}
				}
				
			}
			
			
		}
		
	}
	
	public void analyseUrl(){
		
		Elements activePart = document.select("#content #detail-box .detail-cols.fn-clear .ui_bg6 .box_intro .box_info .option .txtopt a");
		if(activePart.size()>0){
			
			this.entity.setDownPath(activePart.get(0).attr("href"));
		}
		
	}
	
	public void analyse(){
		
		this.analyseTags();
		this.analyseTitle();
		this.analyseUrl();
		this.analyseMemo();
		
		this.entity.download();
		this.entity.insert();
		
	}

	/**
	 * 地址解析完成
	 * @param args
	 */
	public static void main(String[] args) {
		
		YmwenNetDetail detail = new YmwenNetDetail("http://www.335xs.cc/book/19282.html");
		
		//detail.analyseTags();
		
		detail.analyseMemo();
	}
	
}
